const simpleConsole = document.getElementById('simple-console');

let logCount = 0;

function showOnPage(message) {
    if (logCount++ % 2 === 0)
        simpleConsole.innerHTML += `<div style="background-color: cornsilk; margin: 5px 5px;">${message}</div>`;
    else
        simpleConsole.innerHTML += `<div style="background-color: azure; margin: 5px 5px;">${message}</div>`;
}

const originalLog = console.log;
console.log = function (...args) {
    originalLog(...args);
    showOnPage(args.join(' '));
};

//TODO/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

let actorsBookArr = [];
let actorsBookMapArr = [];
let seriesBookArr = [];
let seriesBookMapArr = [];
const bookMap = new Map();
let actorsCountMapArr = [];
let seriesCountMapArr = [];
const parentBookMap = new Map();

window.onload = function () {
    getBookmarksTree();
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "getActorsBookmarks") {
        sendResponse({actorsBookArr: actorsBookArr, actorsBookMapArr: actorsBookMapArr})
    }
    if (request.action === "getSeriesBookmarks") {
        sendResponse({seriesBookArr: seriesBookArr, seriesBookMapArr: seriesBookMapArr})
    }
    if (request.action === "getCountMapArr") {
        sendResponse({actorsCountMapArr: actorsCountMapArr, seriesCountMapArr: seriesCountMapArr})
    }
    if (request.action === "updateBookmark") {
        if (request.type === '2') bacthOpenTabs(request, sendResponse)
        else sendResponse(updateBookmark(request.actors, request.cDate, request.bookName, request.bookUrl));
        if (request.pageNo > 1) sendResponse({});
    }
    // 保持消息通道开放（关键）
    return true;
});

function getBookmarksTree() {
    chrome.bookmarks.getTree(bookmarks => {
        console.log("获取书签 ===>> 开始");
        bookmarks[0].children[0].children.forEach(bookmark => {
            if (!bookmark.title.includes("X-JK")) return;

            bookmark.children.forEach(bm => {
                if (!bm.children) return;

                bm.children.forEach(bbm => {
                    let aHref = bbm.url.split('?')[0].replace('https://javdb.com', '');
                    let leftArr = bbm.title.split(' | ')[0].split(' ');
                    let dateStr = leftArr[leftArr.length - 1];
                    if (dateStr.length === 8) dateStr = '20' + dateStr;
                    let chedckDateStr = bbm.title.substring(bbm.title.lastIndexOf('JavDB ') + 5);

                    let count = 0;
                    let left = bbm.title.split('] ')[0];
                    if (left.includes("更新")) count = left.replace('[更新-', '');
                    bbm.count = count;

                    if (bm.title.includes("系列")) {
                        seriesBookArr.push(aHref);
                        seriesBookMapArr.push(aHref + '@' + dateStr + '@' + chedckDateStr);
                        seriesCountMapArr.push(aHref + '@' + count);

                        if (!bbm.url.includes('f=download'))
                            chrome.bookmarks.update(bbm.id, {url: bbm.url + '?f=download'});
                    } else {
                        actorsBookArr.push(aHref);
                        actorsBookMapArr.push(aHref + '@' + dateStr + '@' + chedckDateStr);
                        actorsCountMapArr.push(aHref + '@' + count);
                    }
                    bookMap.set(aHref, bbm);
                });
                parentBookMap.set(bm.title.split(' [')[0], bm.id);

                if (bm.title.includes("UnChecked"))
                    bm.children.sort((a, b) => a.count - b.count);
                else bm.children.sort((a, b) => b.count - a.count);
                let length = 0;
                bm.children.forEach(bbm => {
                    // console.log("排序书签 ===>> ", bbm.count, " ===>> ",bbm.title, );
                    chrome.bookmarks.move(bbm.id, {parentId: bbm.parentId, index: length++});
                });
            });
        })
        console.log("获取书签 ===>> 结束");
    });
}

async function bacthOpenTabs(request, sendResponse) {
    for (let i = 0; i < request.movieList.length; i++) {
        let randomInt = getRandomInt(1111, 2222);
        await sleep(randomInt);
        chrome.tabs.create({url: request.movieList[i].href, active: false});
    }
    await sleep(1234);
    sendResponse(updateBookmark(request.actors, request.cDate, request.bookName, request.bookUrl));
}

function updateBookmark(key, cDate, bookName, bookUrl) {
    console.log("更新书签 ===>> ", key, cDate, bookName, bookUrl);

    const today = getFormattedDate(new Date());
    let parentId = 0;
    if (key.includes('series')) {
        parentId = parentBookMap.get('Done-系列');
        seriesBookMapArr = seriesBookMapArr.filter(item => !item.includes(key));
        seriesBookMapArr.push(key + '@' + cDate + '@' + today);
        seriesBookArr.push(key);
    } else {
        actorsBookMapArr = actorsBookMapArr.filter(item => !item.includes(key));
        actorsBookMapArr.push(key + '@' + cDate + '@' + today);
        actorsBookArr.push(key);
        if (new Date(cDate) - new Date('2024-01-01') < 0)
            parentId = parentBookMap.get('Done-JK-23');
        if (cDate.includes('2024')) parentId = parentBookMap.get('Done-JK-24');
        if (cDate.includes('2025')) parentId = parentBookMap.get('Done-JK-25');
    }

    let bbm = bookMap.get(key);
    console.log("获取书签 ===>> ", key, cDate, parentId, bbm);
    if (bbm === undefined) {
        console.log("创建书签 ===>> ", key, cDate, parentId);
        chrome.bookmarks.create({parentId: parentId, title: bookName + today, url: bookUrl});
        return {code: true, key: key, cDate: cDate};
    }

    let titleArr = bbm.title.split("\] ");
    titleArr = titleArr[titleArr.length - 1].split(' | ');
    let right = titleArr[1].split(' ')[0] + ' ' + today;
    let left = titleArr[0].split(' ')[0] + ' ' + cDate;
    bbm.title = left + ' | ' + right;
    console.log("修改书签 ===>> ", key, cDate, parentId);
    chrome.bookmarks.update(bbm.id, {title: bbm.title});

    console.log("移动书签 ===>> ", key, cDate, parentId);
    chrome.bookmarks.move(bbm.id, {parentId: parentId, index: 0});
    return {code: true, key: key, cDate: cDate};
}

// chrome.bookmarks.onCreated.addListener((id, bookmark) => {
//     console.log('用户手动添加书签:', id, bookmark);
//     let aHref = bookmark.url.split('?')[0].replace('https://javdb.com', '');
//     let leftStr = bookmark.title.split('] ')[0];
//     let leftArr = leftStr.split(' ');
//     let dateStr = leftArr[leftArr.length - 1];
//     let count = 0;
//     if (leftStr.includes("更新")) count = leftStr.replace('[更新-', '');
//     if (aHref.includes('actors')) {
//         actorsBookArr.push(aHref);
//         actorsBookMapArr.push(aHref + '@' + dateStr);
//         actorsCountMapArr.push(aHref + '@' + count);
//     }
//     if (aHref.includes('series')) {
//         seriesBookArr.push(aHref);
//         seriesBookMapArr.push(aHref + '@' + dateStr);
//         seriesCountMapArr.push(aHref + '@' + count);
//     }
//     bookMap.set(aHref, bookmark);
// });

// chrome.bookmarks.onRemoved.addListener((id, bookmark) => {
//     console.log('用户手动删除书签:', id, bookmark);
//     let aHref = bookmark.url.split('?')[0].replace('https://javdb.com', '');
//     let leftStr = bookmark.title.split('] ')[0];
//     let leftArr = leftStr.split(' ');
//     let dateStr = leftArr[leftArr.length - 1];
//     let count = 0;
//     if (leftStr.includes("更新")) count = leftStr.replace('[更新-', '');
//     if (aHref.includes('actors')) {
//         actorsBookArr = actorsBookArr.filter(item => !item.includes(aHref));
//         actorsBookMapArr = actorsBookMapArr.filter(item => !item.includes(aHref + '@' + dateStr));
//         actorsCountMapArr = actorsCountMapArr.filter(item => !item.includes(aHref + '@' + count));
//     }
//     if (aHref.includes('series')) {
//         seriesBookArr = seriesBookArr.filter(item => !item.includes(aHref));
//         seriesBookMapArr = seriesBookMapArr.filter(item => !item.includes(aHref + '@' + dateStr));
//         seriesCountMapArr = seriesCountMapArr.filter(item => !item.includes(aHref + '@' + count));
//     }
//     bookMap.delete(aHref);
// });

//TODO///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

document.getElementById('batchUpdateBookmarks')
    .addEventListener('click', batchUpdateBookmarks);

function batchUpdateBookmarks() {
    chrome.bookmarks.getTree(async function (bookmarks) {
        console.log("批量更新书签 ===>> 开始");

        for (let i = 0; i < bookmarks[0].children[0].children.length; i++) {
            let bookmark = bookmarks[0].children[0].children[i];
            // console.log("遍历一级书签", bookmark.title);
            if (!bookmark.title.includes("X-JK")) continue;

            for (let i = 0; i < bookmark.children.length; i++) {
                let bm = bookmark.children[i];
                if (!bm.children) continue;
                chrome.bookmarks.update(bm.id, {title: bm.title.split(" ")[0] + " [" + bm.children.length + "]"});

                let lastCount = 20;
                if (bm.title.includes('UnChecked')) lastCount = 45;
                if (bm.title.includes('23')) lastCount = 30;
                if (bm.title.includes('24')) lastCount = 15;
                if (bm.title.includes('25')) lastCount = 10;
                let filterArr = bm.children.filter(bbm => {
                    let title = bbm.title;
                    bbm.count = bm.title.includes("Done") ? 0 : 9999;
                    if (title.includes('更新')) bbm.count = title.split("] ")[0].replace('[更新-', '');
                    if (!title.includes(" JavDB ")) console.log("XXX ===>> ", title)
                    let lastDateStr = title.split(" JavDB ")[1];
                    let lastDate = lastDateStr.includes("-") ? new Date(lastDateStr) : new Date("1970-07-01");
                    return new Date(today) - lastDate > lastCount * 24 * 60 * 60 * 1000;
                });

                console.log("遍历二级书签 ===>> 开始", bm.title);
                if (bm.title.includes("Done")) {
                    await doneFetch(bm.title, filterArr, 0);
                    console.log("遍历二级书签(Done)结束Fetch", bm.title);
                    bm.children.sort((a, b) => b.count - a.count);
                }

                if (bm.title.includes("UnChecked")) {
                    await unCheckedFetch(bm.title, filterArr, 0);
                    console.log("遍历二级书签(UnChecked) ===>> 结束Fetch", bm.title);
                    bm.children.sort((a, b) => a.count - b.count);
                }
                let length = 0;
                bm.children.forEach(bbm => {
                    chrome.bookmarks.move(bbm.id, {parentId: bbm.parentId, index: length++});
                });
                console.log("遍历二级书签 ===>> 结束", bm.title);
            }
        }

        getBookmarksTree();
        console.log("批量更新书签 ===>> 结束");
    });
}

async function doneFetch(pTitle, children, index) {
    if (!children || children.length === 0) return;
    let bbm = children[index];
    let dateStr = bbm.title.split(' JavDB ')[1];
    if (dateStr.length === 8) dateStr = '20' + dateStr;
    let dateArr = dateStr.split(" ");
    if (dateArr.length === 3) dateStr = dateArr[2] + ' ' + dateArr[3];
    let oldDate = new Date(dateStr);
    let randomInt = getRandomInt(6666, 9999);
    await sleep(randomInt);
    console.log("遍历三级书签Fetch ===>> sleep(" + randomInt + ")", pTitle, bbm.title);
    await fetch(bbm.url)
        .then(response => response.text())
        .then(html => {
            const parser = new DOMParser();
            const dom = parser.parseFromString(html, 'text/html');
            const movieList = dom.querySelector('.movie-list');
            let count = 0;
            movieList.querySelectorAll(".item").forEach(item => {
                let meta = item.querySelector(".meta");
                let newDate = new Date(meta.innerHTML.trim());
                if (newDate > oldDate) count++;
            });
            return count;
        })
        .then(count => {
            let titleArr = bbm.title.split("\] ");
            titleArr = titleArr[titleArr.length - 1].split(' | ');
            let right = titleArr[1].split(' ')[0] + ' ' + today;
            let left = titleArr[0];
            if (count > 0) {
                left = "[更新-" + count + "] " + titleArr[0];
                bbm.count = count;
            }
            let newTitle = left + ' | ' + right;
            chrome.bookmarks.update(bbm.id, {title: newTitle});
        })
        .then(async () => {
            if (index < children.length - 1)
                await doneFetch(pTitle, children, index + 1);
        });
}

async function unCheckedFetch(pTitle, children, index) {
    if (!children || children.length === 0) return;
    let bbm = children[index];
    let randomInt = getRandomInt(6666, 9999);
    await sleep(randomInt);
    console.log("遍历三级书签Fetch ===>> sleep(" + randomInt + ")", pTitle, bbm.title);
    await fetch(bbm.url)
        .then(response => response.text())
        .then(html => {
            const parser = new DOMParser();
            const dom = parser.parseFromString(html, 'text/html');
            if (pTitle.includes('系列')) {
                let paginationListElement = dom.querySelector(".pagination-list");
                if (paginationListElement) {
                    let liList = paginationListElement.querySelectorAll("li");
                    if (liList && liList.length > 1) return liList.length * 40;
                }
                let movieListElement = dom.querySelector(".movie-list");
                return movieListElement.querySelectorAll(".item").length;
            } else {
                const actorSection = dom.querySelector('.section-columns');
                let sectionMetaList = actorSection.querySelectorAll(".section-meta");
                let sectionMeta = sectionMetaList.item(sectionMetaList.length - 1);
                return sectionMeta.innerHTML.split(" ")[0];
            }
        })
        .then(count => {
            let titleArr = bbm.title.split("\] ");
            titleArr = titleArr[titleArr.length - 1].split(' | ');
            let right = titleArr[1].split(' ')[0] + ' ' + today;
            let left = titleArr[0];
            if (count > 0) {
                left = "[更新-" + count + "] " + titleArr[0];
                bbm.count = count;
            }
            let newTitle = left + ' | ' + right;
            chrome.bookmarks.update(bbm.id, {title: newTitle});
        })
        .then(async () => {
            if (index < children.length - 1)
                await unCheckedFetch(pTitle, children, index + 1);
        });
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

const today = getFormattedDate(new Date());

function getFormattedDate(date) {
    // 补零函数，确保两位数显示
    const padZero = (num) => (num < 10 ? '0' + num : num.toString());
    const year = date.getFullYear();
    const month = padZero(date.getMonth() + 1); // 月份从0开始，需加1
    const day = padZero(date.getDate());
    const hours = padZero(date.getHours());
    const minutes = padZero(date.getMinutes());
    const seconds = padZero(date.getSeconds());
    // 拼接成目标格式
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

//TODO///////////////////////////////////////////////////////////////////////////////////////////////////////////////////



